from celery import shared_task
from celery.schedules import crontab
from django.utils import timezone
from .models import HostPassword, Host, DailyStat, City, DataCenter
import random
import string


@shared_task
def rotate_host_passwords():
    hosts = Host.objects.filter(is_active=True)
    for host in hosts:
        password_obj, created = HostPassword.objects.get_or_create(host=host)
        # Generate random password
        length = 16
        chars = string.ascii_letters + string.digits + '!@#$%^&*'
        new_password = ''.join(random.choice(chars) for _ in range(length))

        # Save old password to history
        history = password_obj.history or []
        history.append({
            'password': password_obj.root_password,
            'changed_at': timezone.now().isoformat()
        })

        # Update password
        password_obj.root_password = new_password
        password_obj.history = history[:10]  # Keep last 10 passwords
        password_obj.save()


@shared_task
def generate_daily_stats():
    today = timezone.now().date()
    cities = City.objects.all()

    for city in cities:
        data_centers = DataCenter.objects.filter(city=city)
        for dc in data_centers:
            host_count = Host.objects.filter(data_center=dc, is_active=True).count()
            DailyStat.objects.create(
                date=today,
                city=city,
                data_center=dc,
                host_count=host_count
            )